<template>
  <div class="handle-box">
    <el-dialog
        v-model="handleDialogVisible"
        title="流程申请"
        width="50%"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        draggable
        style="height: auto;
        background-color:#fff;
        padding-bottom: 3vh;
        "
        :before-close="handleClose"
    >
      <div class="leave-detail-box">
        <div class="top">
          <div class="t1">
            <div class="t1-item">
              <div class="t1-title">申请时间</div>
              <div class="t1-con">{{computeDate(detail_form.created_at)}}</div>
            </div>
          </div>
          <div class="t1">
            <div class="t1-item">
              <div class="t1-title">标题</div>
              <div class="t1-con">{{detail_form.title}}</div>
            </div>
          </div>
          <div
              class="t1"
              style="height: auto;word-wrap: break-word;word-break: normal;"
          >
            <div class="t1-item">
              <div class="t1-title">描述</div>
              <div
                  class="t1-con"
                  style="height: auto;"
              >
                {{detail_form.content}}
              </div>
            </div>
          </div>
          <div class="t1">
            <div class="t1-item">
              <div class="t1-title">附件</div>
              <div class="t1-con">
                <el-button
                    @click="downloadFile(detail_form.borrow_id,detail_form.uploaderName,detail_form.file)"
                    type="info"
                >
                  下载附件
                </el-button>
                <el-button
                    @click="previewFile(detail_form)"
                    type="info"
                >
                  预览附件
                </el-button>
              </div>
            </div>
          </div>
        </div>
        <div class="bot">
          <div class="b1">
            <div class="b1-item">
              <div class="b1-title">审核状态</div>
              <div class="b1-con">
                <div v-if="detail_form.status === 0">已提交</div>
                <div v-if="detail_form.status === 1">审核中</div>
                <div v-if="detail_form.status === 2">已完成</div>
                <div v-if="detail_form.status === 3">已撤销</div>
                <div v-if="detail_form.status === 4">待修改</div>
              </div>
            </div>
            <div class="b1-item">
              <div class="b1-title">当前审核人</div>
              <div
                  class="b1-con"
                  style="font-family: dingding"
              >
                {{ detail_form.operatorName }}
              </div>
            </div>
          </div>
          <div class="b1">
            <div class="b1-item">
              <div class="b1-title" style="width: 20.5%">抄送人</div>
              <div class="b1-con" >
                <div
                    class="b1-con"
                    v-if="detail_form.copy.length"
                    style="display: flex;font-family: dingding"
                >
                  <div class="item"
                       v-for="item in detail_form.copy" :key="item.approve_id"
                       style="width: 30%"
                  >
                    {{ item }}
                  </div>
                </div>
                <div class="b1-con" v-else>
                  无
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="no-border" v-if="isFormShow">
        <div class="form-box" v-if="detail_form.status !== 2">
          <div class="form-item" style="height: 10vh;line-height: 10vh">
            <div class="title">
              审批描述
            </div>
            <div class="input">
              <el-input
                  v-model="submit_form.reason"
                  style="width: 99%;height: 9.5vh"
                  type="textarea"
                  placeholder="请输入审批意见"
              />
            </div>
          </div>
          <div class="form-item" style="height: 5vh;line-height: 5.5vh">
            <div class="title">
              审批意见
            </div>
            <div class="input">
              <el-select
                  v-model="submit_form.result"
                  placeholder="请选择审批结果"
                  size="large"
                  style="width: 99%;height: 4.5vh"
              >
                <el-option
                    v-for="item in resultOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </div>
          </div>
          <div class="form-item" style="height: 5vh;line-height: 5.5vh">
            <div class="title">
              相关附件(如有)
            </div>
            <div class="input">
              <el-upload
                  v-model:file-list="submit_form.file"
                  class="upload-demo"
                  :action="createURL"
                  multiple
                  :limit="1"
                  :on-exceed="handleExceed"
                  :on-change="handleSealFileChange"
                  :on-success="handleSealFileSuccess"
                  :auto-upload="false"
              >
                <!--style="    height: 90%;display: flex;flex-direction: column;"-->
                <el-button size="small">点击上传</el-button>
                <div class="el-upload__text" style="font-family: dingding;margin-left: 1vw">
                  上传审批附件
                </div>
              </el-upload>
            </div>
          </div>
        </div>
        <div class="form-submit" v-show="detail_form.status !== 2">
          <el-button
              type="primary"
              @click="submitResult"
              style="margin-top: 5vh;"
          >
            提交
          </el-button>
        </div>
      </div>
      <div class="approve-result" v-show="detail_form.status === 2">
        <div class="form-item" style="height: 5vh;line-height: 5.5vh">
          <div class="title">
            审批结果
          </div>
          <div class="input">
            <div v-if="detail_form.result === 1">
              通过
            </div>
            <div v-if="detail_form.result === 0">
              拒绝
            </div>
            <div v-if="detail_form.result === null">
              待审批
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import {ElButton, ElDialog, ElMessage, ElRadioGroup, ElRadio, ElInput, ElCascader, ElUpload} from "element-plus"
import {onMounted, reactive, ref, defineEmits, watch} from "vue"
import {checkUserByRole, getCurrentFlow, operateLeaveFlow} from "@/api"
import emitter from "@/lib/eventBus"
import {useRoute} from "vue-router"
import {doSealCheck, downSeal, getNextSealOperator, getOperators, getSealApproveDetails} from "@/api/OA/Seal"
import {clearObject, computeDate, createMsg, emptyObject, hasEmptyValue, isPDF, processSealFileJSON} from "@/lib/utils"
import {createURL, previewYRL} from "@/api/http"
import {checkApp, createApp, download, getApproveById} from "@/api/OA/Approve"
import {doBorrowCheck, downloadBorrow, getBorrowById} from "@/api/Borrow/Borrow"

const route = useRoute()
const emits = defineEmits(['reloadHandle','reloadAll','reloadGoing'])

let user_info
const handleDialogVisible = ref(false)
const historyOperator = ref([])
const options = ref([])
const rules = {
  node:{},
  next:{},
  reason:{},
  result:{},
}
const hasNext = ref(true)
let seal_file = ref([])

const resultOptions = [
  {
    value: 1,
    label: '通过',
  },{
    value: 0,
    label: '拒绝',
  },{
    value: 2,
    label: '驳回修改',
  }
]

const isFormShow = ref(true)

const hasNextOperator = ref(true)

let currentFlowId

let detail_form = reactive({

})

let submit_form = reactive({
  nextOperator:'',
  reason:null,
  result:null,
  hasNext:1,
})


onMounted(() => {
  console.log(route.path)
  if(route.path === '/handled'){
    hasNext.value = false
    isFormShow.value = false
  }
  getUserInfo()
  // getUserList()
})

const getUserInfo = () => {
  user_info = JSON.parse(localStorage.getItem('syhyDocManSys'))
}

const getUserList = async () => {
  try {
    let arr = []
    const {data:res} = await getOperators()
    if (res.code === 200){
      res.data.forEach(item=>{
        let child = []
        item.users.forEach(item2=>{
          child.push({
            label:item2.user_name,
            value:item2.user_id
          })
        })
        arr.push({
          value:item.roleId,
          label:item.roleName,
          children:child
        })
      })
      options.value = arr
    }
  } catch (e) {
    console.log(e)
  }
}

const showDetails = async (id) => {
  try {
    currentFlowId = id
    console.log(id)
    await getUserList(id)
    const {data:res} = await getBorrowById(id)
    if(res.code === 200){
      detail_form = res.data
      handleDialogVisible.value = true
    } else {
      ElMessage({
        message:'获取失败',
        type:'error'
      })
    }
  } catch (e) {
    console.log(e)
  }
}



// 当超出限制时，执行的钩子函数
const handleExceed = () => {
  createMsg('单次只能上传一个文件','warning')
}

const handleSealFileChange = (file) => {
  console.log(file.raw,'file.raw')
  seal_file.value.push(file.raw)
}

//
const handleSealFileSuccess = (file) => {
  console.log(file,'s')
}

const submitResult = async () => {
  try {
    // 先做表单判断 用印流程一定按规定好的节点审批
    if (submit_form.result === null || !submit_form.reason) return createMsg('意见和结果不能为空','error',false)
    const form = new FormData();
    form.append("userId", user_info.id);
    form.append("borrowId", currentFlowId);
    form.append("describe", submit_form.reason);
    form.append("result", submit_form.result);
    form.append("file",seal_file.value[0])
    const {data:res} = await doBorrowCheck(form)
    if (res.code === 200) {
      handleClose() // 关闭 刷新
      emitter.emit('reloadBadge',user_info.id)
      return createMsg('操作成功!','success',true)
    } else {
      handleClose() // 关闭 刷新
      return createMsg('操作失败','info',true)
    }
  } catch (e) {
    console.log(e)
  }
}

const isLastItem = (index) => {
  return index === historyOperator.value.length - 1;
}

const handleClose = () => {
  historyOperator.value = []
  submit_form = clearObject(submit_form)
  submit_form.operatorId = null
  options.value = []
  if(route.path === '/OA/seal/handle/all'){
    emits('reloadAll')
  } else if (route.path === '/OA/seal/handle/going'){
    emits('reloadGoing')
  }
  handleDialogVisible.value = false
}

const downloadSealFile = async (id) => {
  try {
    const res = await downSeal(id)
    const type = processSealFileJSON(detail_form.file)
    // 创建一个新的 URL 对象，并生成一个下载链接
    const url = window.URL.createObjectURL(new Blob([res.data],
        { type: type.type }));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', `${detail_form.uploaderName}的用印附件.${type.ext}`); // 设置下载的文件名
    link.style.display = 'none' // 隐藏元素
    document.body.appendChild(link);
    link.click();

    // 清理 DOM 和释放 URL 对象
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
  } catch (e) {
    console.log(e)
  }
}

const previewFile = async (row) => {
  if (!isPDF(row)) return createMsg('仅pdf文件支持在线预览','info',true)
  await window.open(`${previewYRL}/previewBO?approveId=${row.borrow_id}`)
}

const downloadFile = async (id,uploaderName,file) => {
  try {
    const res = await downloadBorrow(id)
    const type = processSealFileJSON(file)
    // 创建一个新的 URL 对象，并生成一个下载链接
    const url = window.URL.createObjectURL(new Blob([res.data],
        { type: type.type }));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', `${uploaderName}的用印附件.${type.ext}`); // 设置下载的文件名
    link.style.display = 'none' // 隐藏元素
    document.body.appendChild(link);
    link.click()
    // 清理 DOM 和释放 URL 对象
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
  } catch (e) {
    console.log(e)
  }
}


watch([()=>submit_form.hasNext,()=>submit_form.result],()=>{
  if (!submit_form.hasNext){
    hasNextOperator.value = false
  } else {
    hasNextOperator.value = true
  }
  if (submit_form.result === 0 || submit_form.result === 2){
    hasNextOperator.value = false
  }
  if (submit_form.result === 2){
    hasNextOperator.value = false
    submit_form.hasNext = 0
  }
})

defineExpose({
  showDetails,
})

</script>

<style scoped lang="less">
.handle-box{
  box-sizing: border-box;
  height: 95%;
  .leave-detail-box{
    width: 95%;
    margin: 3vh auto;
    .top{
      background-color:#fff;
      border: 1px solid rgb(238,238,238);
      display: flex;
      flex-direction: column;
      margin-top: 2vh;
      .t1{
        width: 100%;
        font-size: 1.6vh;
        border-bottom: 1px solid rgb(238,238,238);
        height: 5vh;
        line-height: 5vh;
        display: flex;
        justify-content: space-between;
        .t1-item{
          width: 100%;
          display: flex;
          justify-content: left;
          .t1-title{
            font-weight: 600;
            text-align: center;
            width: 30%;
            background-color: rgb(250,250,250);
            border-left: 1px solid rgb(250,250,250);
            border-right: 1px solid rgb(250,250,250);
          }
          .t1-con{
            text-align: left;
            background-color: #fff;
            width: 60%;
            padding-left: 1vw;
          }
        }
      }
      .t2{
        width: 100%;
        font-size: 1.6vh;
        background-color:#fff;
        height: 5vh;
        line-height: 5vh;
        display: flex;
        .t2-item{
          width: 100%;
          display: flex;
          justify-content: left;
          .t2-title{
            font-weight: 600;
            text-align: center;
            width: 15%;
            background-color: rgb(250,250,250);
            border-left: 1px solid rgb(250,250,250);
            border-right: 1px solid rgb(250,250,250);
          }
          .t2-con{
            text-align: left;
            background-color: #fff;
            width: 60%;
            padding-left: 1vw;
          }
        }
      }
    }
    .bot{
      background-color:#fff;
      border: 1px solid rgb(238,238,238);
      //border-left: none;
      margin-top: 3vh;
      display: flex;
      flex-direction: column;
      .b1{
        display: flex;
        width: 100%;
        font-size: 1.6vh;
        border-bottom: 1px solid rgb(238,238,238);
        height: 5vh;
        line-height: 5vh;
        .b1-item{
          width: 100%;
          display: flex;
          justify-content: left;
          .b1-title{
            font-weight: 600;
            text-align: center;
            width: 49%;
            background-color: rgb(250,250,250);
            border-left: 1px solid rgb(250,250,250);
            border-right: 1px solid rgb(250,250,250);
          }
          .b1-con{
            text-align: left;
            background-color: #fff;
            width: 60%;
            padding-left: 1vw;
          }
        }
      }
      .b2{
        background-color:#fff;
        width: 100%;
        font-size: 1.6vh;
        height: 5vh;
        line-height: 5vh;
        display: flex;
        .b2-item{
          width: 100%;
          display: flex;
          justify-content: left;
          .b2-title{
            font-weight: 600;
            text-align: center;
            width: 14%;
            background-color: rgb(250,250,250);
            border-left: 1px solid rgb(250,250,250);
            border-right: 1px solid rgb(250,250,250);
          }
          .b2-con{
            text-align: left;
            background-color: #fff;
            width: 60%;
            padding-left: 1vw;
            display: flex;
            line-height: 5vh;
            align-items: center;
          }
        }
      }
    }
  }

  .no-border{
    .form-box{
      display: flex;
      flex-direction: column;
      background-color: #fff;
      border: 1px solid rgb(238, 238, 2378);
      border-bottom: none;
      width: 95%;
      margin: 0 auto;
      .form-item{
        display: flex;
        justify-content: left;
        height: auto;
        border-bottom: 1px solid rgb(238, 238, 238);
        font-size: 1.6vh;
        .title{
          width: 14%;
          text-align: center;
          border-right: 1px solid rgb(238, 238, 238);
          background-color: rgb(250, 250, 250);
          font-weight: 600;
        }
        .input{
          width: 85%;
          text-align: left;
          padding-left: 1vw;
        }
      }
    }
    .form-submit{
      margin: 2vh auto 0 auto;
      border: none;
      width: 95%;
      text-align: right;
    }
  }

  .approve-result{
    display: flex;
    flex-direction: column;
    background-color: #fff;
    border: 1px solid rgb(238, 238, 2378);
    border-bottom: none;
    width: 95%;
    margin: 0 auto;
    .form-item{
      display: flex;
      justify-content: left;
      height: auto;
      border-bottom: 1px solid rgb(238, 238, 238);
      font-size: 1.6vh;
      .title{
        width: 14%;
        text-align: center;
        border-right: 1px solid rgb(238, 238, 238);
        background-color: rgb(250, 250, 250);
        font-weight: 600;
      }
      .input{
        width: 85%;
        text-align: left;
        padding-left: 1vw;
      }
    }
  }
}
:deep(.el-dialog__header ){
  text-align: left !important;
  font-weight: 600;
}
:deep(.el-dialog__body){
  padding: 0 !important;
}
:deep(.el-textarea__inner ){
  height: 9vh;
}
.visible{
  display: none;
}
</style>
